package com.cskaoyan.user.service.impl;

import com.cskaoyan.mall.commons.constant.SysRetCodeConstants;
import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.user.constants.UserRetCode;
import com.cskaoyan.user.converter.UserConverterMapper;
import com.cskaoyan.user.dal.entitys.Member;
import com.cskaoyan.user.dal.entitys.UserVerify;
import com.cskaoyan.user.dal.persistence.MemberMapper;
import com.cskaoyan.user.dal.persistence.UserVerifyMapper;
import com.cskaoyan.user.form.UserRegisterRequest;
import com.cskaoyan.user.form.UserVerifyRequest;
import com.cskaoyan.user.service.IUserRegisterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import tk.mybatis.mapper.entity.Example;

import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 *
 * @since 2022/08/24 21:49
 * @author sunxuJ
 */
@Transactional
@Service
public class UserRegisterServiceImpl implements IUserRegisterService {

    @Autowired
    MemberMapper memberMapper;
    @Autowired
    UserVerifyMapper userVerifyMapper;
    @Autowired
    UserConverterMapper userConverterMapper;
    @Autowired
    JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    String email;

    @Override
    public void register(UserRegisterRequest request) {

        //用户名和email不能重复
        Example example = new Example(Member.class);
        example.createCriteria().orEqualTo("username",request.getUserName())
                .orEqualTo("email",request.getEmail());
        List<Member> members = memberMapper.selectByExample(example);
        if(members.size()>0){
            throw new BizException(SysRetCodeConstants.DATA_REPEATED.getCode(),SysRetCodeConstants.DATA_REPEATED.getMessage());
        }

        //向用户表插入数据
        Member member = userConverterMapper.userRegisterRequestToMember(request);
        String password = member.getPassword();
        String pwdAfterEncode = DigestUtils.md5DigestAsHex(password.getBytes());
        member.setPassword(pwdAfterEncode);
        member.setCreated(new Date());
        member.setUpdated(new Date());
        memberMapper.insertSelective(member);

        //向用户认证表插入数据
        UserVerify userVerify = new UserVerify();
        userVerify.setUsername(request.getUserName());
        userVerify.setRegisterDate(new Date());
        @NotNull String uuid = request.getUserName() + request.getUserPwd() + UUID.randomUUID().toString();
        userVerify.setUuid(uuid);
        userVerify.setIsVerify("N");
        userVerify.setIsExpire("N");
        userVerifyMapper.insertSelective(userVerify);

        //发送邮件
        new Thread(new Runnable() {
            @Override
            public void run() {
                //bymosszxppmthbab
                SimpleMailMessage message = new SimpleMailMessage();
                message.setFrom(email);
                message.setTo(request.getEmail());
                message.setSubject("csmall商城激活");
                message.setText("http://localhost:8099/user/verify?uid=" + uuid + "&username=" + request.getUserName());
                javaMailSender.send(message);
            }
        }).start();
    }


    @Transactional
    @Override
    public void verify(UserVerifyRequest request) {
        Example example = new Example(UserVerify.class);
        example.createCriteria().andEqualTo("username",request.getUsername())
                .andEqualTo("uuid",request.getUid())
                .andEqualTo("isVerify","N")
                .andEqualTo("isExpire","N");
        //判断数据库中是否存在该数据
        List<UserVerify> userVerifies = userVerifyMapper.selectByExample(example);
        if(userVerifies.size() == 0){
            //TODO
            throw new BizException(UserRetCode.ACTIVATE_FAIL.getCode(),UserRetCode.ACTIVATE_FAIL.getMessage());
        }
        //修改用户认证表
        UserVerify userVerify = new UserVerify();
        userVerify.setIsVerify("Y");
        userVerifyMapper.updateByExampleSelective(userVerify,example);

        //修改用户表
        Example memberExample = new Example(Member.class);
        memberExample.createCriteria().andEqualTo("username",request.getUsername())
                .andEqualTo("isVerified","N");
        Member member = new Member();
        member.setIsVerified("Y");
        memberMapper.updateByExampleSelective(member, memberExample);
    }
}
